package com.supreme.simpleserver.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

@Component
@Slf4j
public class TransactionUtils {

    //事务管理器
    private final DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    public TransactionUtils(DataSourceTransactionManager dataSourceTransactionManager) {
        this.dataSourceTransactionManager = dataSourceTransactionManager;
    }

    public TransactionStatus begin() {
        TransactionStatus transaction = this.dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
        log.info("begin: {}", transaction);
        return transaction;
    }

    public void commit(TransactionStatus transactionStatus) {
        this.dataSourceTransactionManager.commit(transactionStatus);
    }

    public void rollback(TransactionStatus transactionStatus) {
        this.dataSourceTransactionManager.rollback(transactionStatus);
    }
}
